package com.freedom.supercoin.base_library.dialog;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;


import com.freedom.supercoin.base_library.R;

import java.lang.reflect.Field;


/**
 * Created by chenjy on 2016/12/5.
 * <p>
 * 基础FragmentDialog
 */
public abstract class BaseDialog extends DialogFragment {

    protected FragmentActivity mActivity;
    protected View mParent;

    protected abstract int setContentId();

    protected abstract void initView();

    protected abstract void initData();

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        if (getDialog() == null) {
            Context context = getContext();
            while (context instanceof ContextWrapper) {
                if (context instanceof FragmentActivity) {
                    break;
                }
                context = ((ContextWrapper) context).getBaseContext();
            }
            if (context instanceof FragmentActivity) {
                ((FragmentActivity) context).finish();
                return;
            } else {
                setShowsDialog(false);
            }
        }
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Window window = getDialog().getWindow();
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        window.setBackgroundDrawableResource(R.color.Transparent);
        mActivity = getActivity();
        mParent = inflater.inflate(setContentId(), container, false);
        initView();
        initData();
        return mParent;
    }

    protected <T extends View> T findView(@IdRes int id) {
        return (T) mParent.findViewById(id);
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        synchronized (this) {
            if (isAdded()) {
                return;
            }
            if (!isVisible() && !isRemoving() && null == manager.findFragmentByTag(tag)) {
                FragmentTransaction ft = manager.beginTransaction();
                ft.add(this, tag);
                // 这里吧原来的commit()方法换成了commitAllowingStateLoss()
                ft.commitAllowingStateLoss();
            }
        }
    }

    @Override
    public void dismiss() {
        Activity activity = getActivity();
        if (activity != null && !activity.isFinishing() && getDialog() != null && getDialog().isShowing()) {
            dismissAllowingStateLoss();
        }
    }

}
